package com.witframework.core;

import java.util.HashMap;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;

/**
 * @author wuxinyang
 */
public class BeanFactory {

	private static ApplicationContext  ctx =null;

	private static HashMap<String, ClassPathXmlApplicationContext> context=new HashMap<String, ClassPathXmlApplicationContext>();
	private BeanFactory(){

	}
	public static void instance(){

	}
	public static WebApplicationContext getWebApplicationContext(){
		if(ctx!=null && ctx instanceof WebApplicationContext)
			return (WebApplicationContext)ctx;
		return null;
	}
	public static void instance(WebApplicationContext webApplicationContext){
		ctx=webApplicationContext;
	}
	public static ApplicationContext getApplicationContext(){
		if(ctx==null){
			init();
		}
		return ctx;
	}
	public static Object getBean(String beanName) {		
		if(ctx==null){
				init();
		}
		Object bean= ctx.getBean(beanName);		
		return bean;
	}
	public static Object getBeanNoException(String beanName){
		try{
			return getBean(beanName);
		}catch(NoSuchBeanDefinitionException e){
			return null;
		}
	}
	public static void refreshApplicationContext(){
		if(ctx instanceof AbstractApplicationContext){
			((AbstractApplicationContext)ctx).refresh();
		}
		else if(ctx instanceof GenericWebApplicationContext){//not excute
			ctx=null;
			init();
		}

	}
	private static void init(){
		if(ctx==null){
			try {
				String context=ApplicationProperties.getProperty("spring.context");
				String[] contextFile=context.trim().split("\\,");
				ctx = new ClassPathXmlApplicationContext(contextFile);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	public static Object getBean(String beanName,String config){
		ClassPathXmlApplicationContext appContext=null;
		if((appContext=(ClassPathXmlApplicationContext)context.get(config))==null){
			appContext= new ClassPathXmlApplicationContext(config.split("\\,"));
			context.put(config,appContext);
		}
		return appContext.getBean(beanName);
	}
}
